/*
 * SqlCondition.h
 *
 *  Created on: 2018年4月6日
 *      Author: chuanjiang.zh@qq.com
 */

#ifndef UTIL_SQLCONDITION_H_
#define UTIL_SQLCONDITION_H_

#include "TStringUtil.h"

namespace util
{

class SqlCondition
{
public:
    template <class Container>
    static std::string join(const Container& cont, char sp)
    {
        std::ostringstream oss;
        int index = 0;
        typename Container::const_iterator it = cont.begin();
        while (it != cont.end())
        {
            if (index > 0)
            {
                oss << sp;
            }
            oss << '\'' << *it << '\'';

            ++it;
            index++;
        }
        return oss.str();
    }

	template <class Container>
	static std::string joinNumber(const Container& cont, char sp)
	{
		std::ostringstream oss;
		int index = 0;
		typename Container::const_iterator it = cont.begin();
		while (it != cont.end())
		{
			if (index > 0)
			{
				oss << sp;
			}
			oss << *it;

			++it;
			index++;
		}
		return oss.str();
	}

public:
	SqlCondition():
		m_count()
	{
	}

	virtual ~SqlCondition()
	{
	}

	SqlCondition& operator += (const std::string& statement)
	{
		return join(statement);
	}

	SqlCondition& join(const std::string& statement)
	{
		if (m_count > 0)
		{
			m_oss << " and ";
		}

		m_oss << statement;
		m_count ++;
		return *this;
	}

	SqlCondition& joinOr(const std::string& statement)
	{
		if (m_count > 0)
		{
			m_oss << " or ";
		}

		m_oss << statement;
		m_count ++;
		return *this;
	}

	std::string get() const
	{
		return m_oss.str();
	}

	std::string get(const std::string& whereString) const
	{
		std::string str(whereString);
		str += ' ';
		str += m_oss.str();
		return str;
	}

	std::string getWithWhere() const
	{
		if (m_count > 0)
		{
			return get(" where ");
		}
		else
		{
			return "";
		}
	}

	size_t size() const
	{
		return m_count;
	}

	size_t	m_count;

	std::ostringstream	m_oss;

};


} /* namespace util */

#endif /* UTIL_SQLCONDITION_H_ */
